﻿using System;
using System.Linq;
using System.Windows;
using Microsoft.Win32;
using System.Threading;
using FrameWork.Language;
using System.Windows.Data;
using System.Threading.Tasks;
using FrameWork.UI.ControlsEx;
using System.Windows.Controls;
using System.Collections.Generic;

namespace FrameWork.Npoi.Helper
{
    public class DataGridExportHelper
    {
        /// <summary>
        /// 获取excel保存路径
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool TryGetSavePath(string fileName, out string path)
        {
            path = string.Empty;
            SaveFileDialog sfd = new SaveFileDialog
            {
                //设置文件类型
                Filter = "Excel(*.xls)|*.xls|Excel(*.xlsx)|*.xlsx",
                //设置默认文件类型显示顺序
                FilterIndex = 2,
                //保存对话框是否记忆上次打开的目录
                RestoreDirectory = true
            };
            sfd.FileName = fileName;
            bool? result = sfd.ShowDialog();
            if (!result.HasValue || result.Value == false)
                return false;

            path = sfd.FileName;
            return true;
        }

        /// <summary>
        /// 获取DataGrid显示的属性
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetExportPropertyName(DataGrid table)
        {
            var textCols = table.Columns.Where(p => p is DataGridTextColumn);

            var result = new List<string>();
            foreach (DataGridTextColumn col in textCols)
            {
                if (col.Binding is Binding)
                {
                    var bind = col.Binding as Binding;
                    result.Add(bind.Path.Path);
                }
                else if (col.Binding is MultiBinding)
                {
                    var bind = col.Binding as MultiBinding;
                    if (bind.Bindings.Count > 0 && bind.Bindings[0] is Binding)
                    {
                        result.Add((bind.Bindings[0] as Binding).Path.Path);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 导出当前数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="items"></param>
        public static void Export<T>(DataGrid table, IEnumerable<T> items, string title)
        {
            if (!TryGetSavePath($"{title}.xlsx", out string path))
                return;

            var exporpPropNames = GetExportPropertyName(table);
            Thread.Sleep(new Random().Next(100, 1000));
            if (items == null || items.Count() == 0)
            {
                MessageBox.Show(I18n.Get("没有可导出的数据"));
                return;
            }
            try
            {
                ExportHelper.Export(path, title, exporpPropNames, items);
                MessageBox.Show(I18n.Get("导出成功"));
            }
            catch
            {
                MessageBox.Show(I18n.Get("导出失败"));
            }
        }

        /// <summary>
        /// 导出当前数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="items"></param>
        public static async Task ExportAsync<T>(DataGrid table, IEnumerable<T> items, string title)
        {
            if (!TryGetSavePath($"{title}.xlsx", out string path))
                return;

            var exporpPropNames = GetExportPropertyName(table);
            await Task.Run(() =>
            {
                Task.Delay(new Random().Next(100, 1000));
                if (items == null || items.Count() == 0)
                {
                    MessageBox.Show(I18n.Get("没有可导出的数据"));
                    return;
                }
                try
                {
                    ExportHelper.Export(path, title, exporpPropNames, items);
                    MessageBox.Show(I18n.Get("导出成功"));
                }
                catch
                {
                    MessageBox.Show(I18n.Get("导出失败"));
                }
            });
        }

        /// <summary>
        /// 导出当前数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="table"></param>
        /// <param name="items"></param>
        public static async Task ExportAsync<T>(IEnumerable<T> items, string title)
        {
            if (!TryGetSavePath($"{title}.xlsx", out string path))
                return;
            var exporpPropNames = typeof(T).GetProperties().Where(p => p.Name != "Id").Select(p => p.Name);
            await Task.Run(() =>
            {
                Task.Delay(new Random().Next(100, 1000));
                if (items == null || items.Count() == 0)
                {
                    return;
                }
                try
                {
                    ExportHelper.Export(path, title, exporpPropNames, items);
                }
                catch
                {
                }
            });
        }
    }
}
